<template>
  <div class="main">
    <slot></slot>
    <Page
      transfer
      show-sizer
      :total="pageTotal"
      :current="curPage"
      :page-size="pageSize"
      @on-change="changePage"
      @on-page-size-change="changePageSize"
      class-name="page-operate"
      v-if="showPage"
    ></Page>
  </div>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep';

export default {
  name: 'TablePager',
  data() {
    return {
      curPage: 1,
      pageSize: 10,
      pageTotal: 0,

      sortObj: null,

      dataSort: [],
      dataShow: [],
    };
  },
  props: {
    dataFull: {
      type: Array,
    },
    showPage: {
      type: Boolean,
      default: true,
    },
  },
  watch: {
    dataFull: function (params) {
      this.pageTotal = params.length;
      this.dataSort = cloneDeep(params);
      this.sortData();
    },
  },
  methods: {
    changePage(curPage) {
      this.curPage = curPage;
      const startIndex = (curPage - 1) * this.pageSize;
      this.dataShow = this.dataSort.slice(startIndex, startIndex + this.pageSize);
      this.$emit('change-data', this.dataShow, { page: this.curPage, pageSize: this.pageSize });
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.dataShow = this.dataSort.slice(0, this.pageSize);
      this.$emit('change-data', this.dataShow, { page: this.curPage, pageSize: this.pageSize });
    },
    sortData(paramObj) {
      const sortObj = paramObj || this.sortObj;
      if (!sortObj) {
        this.changePage(this.curPage);
        return;
      }
      this.sortObj = sortObj;

      if (sortObj.column && sortObj.column.sortType === 'custom') {
        if (paramObj) {
          this.$emit('sort-type-custom', sortObj);
        }
        return;
      }

      const key = sortObj.key;
      const type = sortObj.order;

      if (type === 'normal') {
        this.dataSort = cloneDeep(this.dataFull);
        return this.dataSort;
      }

      this.dataSort.sort((a, b) => {
        if (sortObj.column && sortObj.column.sortMethod) {
          return sortObj.column.sortMethod(a[key], b[key], type);
        } else {
          if (type === 'asc') {
            return a[key] > b[key] ? 1 : -1;
          } else if (type === 'desc' || type === 'des') {
            return a[key] < b[key] ? 1 : -1;
          }
        }
      });
      this.changePage(1);
      return this.dataSort;
    },
  },
  mounted() {
    this.pageTotal = this.dataFull.length;
    this.dataSort = cloneDeep(this.dataFull);
    this.changePage(1);

    const tableRef = this.$slots.default[0].componentInstance;
    tableRef.$on('on-sort-change', this.sortData);
  },
};
</script>

<style scoped>
.main {
  position: relative;
  /*overflow: hidden;*/
}

.page-operate {
  float: right;
  margin-top: 20px;
}

.page-operate /deep/ .ivu-page-options {
  position: absolute;
  left: 0px;
  margin: 0;
}
</style>
